import random
import re

from django.core import serializers
from django.db.models import Q
from django.http import JsonResponse, HttpResponse, QueryDict
from django.views.decorators.csrf import csrf_exempt
import json
from django.shortcuts import render

from muluguanli.models import Mulu
from yonghuguanli.models import TdsdUser
from ziyuanguanli.models import TdsdResourceList
from utils import util


# 判断是否登录
@util.user_login
def ztree(request):
    """渲染目录结构页面"""
    try:
        user_id = request.session.get('user_id')
        user = TdsdUser.objects.filter(id=user_id).first()
        context = {'user': user}
        return render(request, 'ztree.html', context)
    except Exception:
        return HttpResponse("服务器异常！请联系超级管理员。。。")


@csrf_exempt
def catalog(request):
    """
    根据用户id获取属于用户的所有目录信息
    :param request:
    :return:
    """
    method = request.method
    if method == 'GET':
        # 获取用户的id并查询
        response_data = {}
        get = request.GET
        user_id = get.get('user_id')
        if not user_id:
            result = Mulu.objects.filter(isdelete=0)
            for i in result:
                response_data.setdefault('data', []).append({
                    "id": i.id,
                    "name": re.findall(r'(.*)0\..*',i.name) if re.findall(r'\.',i.name) else i.name,
                    "parent_id": i.parent_id,
                    "user_id": i.user_id,
                    "isdelete": i.isdelete,
                })
            response_data['msg'] = 'success'
            response_data['code'] = 0
            # 返回信息
            return JsonResponse(response_data)
        else:
            # try:
                user_obj = TdsdUser.objects.filter(id = user_id)
                # 判断是否是超级管理员level_id=0
                if user_obj[0].level_id != 0:
                    # 方案一：不是超级管理员，只能查看操作自己创建的目录信息
                         #rootdir_obj = Mulu.objects.filter(id = user_obj[0].dir_id)
                         #  添加查询逻辑user_di 查找目录信息
                         # 查询依据user_id and isdelete=0,或根目录名字and isdelete=0,查询用户的目录
                         #result = Mulu.objects.filter(Q(isdelete=0,user_id=user_id)|Q(name=rootdir_obj[0].name,isdelete=0))
                    # 方案二：不是超级管理员，可查看根目录下所有的目录信息，只能操作自己创建的目录
                    result = []
                    mulu1 = Mulu.objects.filter(id=user_obj[0].dir_id) # 跟目录对象
                    result += mulu1
                    mulu2 = Mulu.objects.filter(parent_id=mulu1[0].id,isdelete=0) # 二级目录对象
                    if mulu2:
                        result += mulu2
                        for i in mulu2:
                            mulu3 = Mulu.objects.filter(parent_id=i.id,isdelete=0) # 三级目录对象
                            if mulu3:
                                result += mulu3
                else:
                    result = Mulu.objects.filter(isdelete=0)
                for i in result:
                    response_data.setdefault('data',[]).append({
                        "id":i.id,
                        "name":re.findall(r'(.*)0\..*',i.name) if re.findall(r'\.',i.name) else i.name,
                        "parent_id":i.parent_id,
                        "user_id":i.user_id,
                        "isdelete":i.isdelete,
                    })
                response_data['msg'] = 'success'
                response_data['code'] = 0
                # 返回信息
                return JsonResponse(response_data)
            # except Exception :
            #     response_data['msg'] = 'failure'
            #     response_data['code'] = 1
            #     return JsonResponse(response_data)
    elif method == 'PUT': # 根据用户id，增加目录节点
        response_data = {}
        put = QueryDict(request.body)
        pid = put.get('pid')
        # TODO 判断当前节点是否有资源信息绑定，如果有禁止添加节点
        # resource = TdsdResourceList.objects.filter(resource_cate=pid)
        resource = False
        msg = 'failure'
        if not resource:
            a = random.random() # 为能使用pid+name实现唯一查询，name添加随机数
            # name = '新增目录'
            name = '新增目录' + str(a)
            # 在session中获取用户的id
            user_id = request.session['user_id']
            try:
                catalog = Mulu.objects.create(
                    name = name,
                    parent_id = int(pid),
                    # 设置用户的id
                    user_id = user_id,
                )
                catalog.save()
                ztree = Mulu.objects.filter(parent_id=pid, name=name)
                for i in ztree:
                    response_data.setdefault('data', []).append({
                        "id": i.id,
                        "name": i.name,
                        "parent_id": i.parent_id,
                        "user_id": i.user_id,
                        "isdelete": i.isdelete,
                    })
                response_data["msg"] = 'success'
                response_data['code'] = 0
                return JsonResponse(response_data)
            except Exception:
                response_data['msg'] = 'failure'
                response_data['code'] = 1
                return JsonResponse(response_data)
        else:
            response_data['msg'] = 'failure'
            response_data['code'] = 2
            return JsonResponse(response_data)
    elif method == 'PATCH':# 重命名节点名称
        patch = QueryDict(request.body)
        id = patch.get('id')
        name = patch.get('name')
        msg = 'failure'
        if name:
            try:
                ztree = Mulu.objects.get(id=id)
                ztree_name = ztree.name
                if name != ztree_name:
                    pid = ztree.parent_id
                    sub_obj = Mulu.objects.filter(parent_id=pid)
                    name_list=[]
                    for i in sub_obj:
                        name_list.append(i.name)
                    if name not in name_list: # 验证同级目录不能重名
                        ztree.name = name
                        ztree.save()
                        msg = 'success'
                        response_data = {'code': 0, 'msg': msg}
                        return JsonResponse(response_data)
                    else:
                        response_data = {'code': 3, 'msg': msg}
                        return JsonResponse(response_data)
            except Exception:
                response_data = {'code': 1, 'msg': msg}
                return JsonResponse(response_data)
        else:
            response_data = {'code': 2, 'msg': msg}
            return JsonResponse(response_data)
    elif method == 'DELETE':# 删除节点操作
        patch = QueryDict(request.body)
        id = patch.get('id')
        msg = 'failure'
        # 判断当前目录是否有资源信息
        resource = TdsdResourceList.objects.filter(resource_cate=id)
        if not resource:
            try:
                sub_node = Mulu.objects.filter(parent_id=id)  # 判断是否有子目录
                if sub_node:
                    for sub in sub_node:
                        sub_resource = TdsdResourceList.objects.filter(resource_cate=sub.id)
                        if not sub_resource:  # 判断子目录是否有资源信息
                            sub2_node = Mulu.objects.filter(parent_id=sub.id)  # 判断子目录是否有子目录
                            if sub2_node:
                                for sub2 in sub2_node:
                                    sub2_resource = TdsdResourceList.objects.filter(resource_cate=sub2.id)
                                    if not sub2_resource:
                                        sub2.isdelete = 1
                                        sub2.save()
                                    else:
                                        response_data = {'code': 2, 'msg': msg}
                                        return JsonResponse(response_data)
                            sub.isdelete = 1
                            sub.save()
                        else:
                            response_data = {'code': 2, 'msg': msg}
                            return JsonResponse(response_data)
                    a = Mulu.objects.get(id=id)
                    a.isdelete = 1
                    a.save()
                else:
                    b = Mulu.objects.get(id=id)
                    b.isdelete = 1
                    b.save()
                msg = 'success'
                response_data = {'code': 0, 'msg': msg}
                return JsonResponse(response_data)
            except Exception:
                response_data = {'code': 1, 'msg': msg}
                return JsonResponse(response_data)
        else:
            response_data = {'code': 2, 'msg': msg}
            return JsonResponse(response_data)


# 获取目录下的所有资源
@csrf_exempt
def get_resource(request):
    """
    资源只能加到最后一级目录下。
    :param request:
    :return:
    """
    id = request.POST.get('id')
    msg = 'failure'
    # 判断当前id节点是否有子级目录
    try:
        sub_node = Mulu.objects.filter(parent_id=id)
        source_list = []
        #  如果有子目录获取子级目录下的信息
        if sub_node:
            for sub in sub_node:
                # 再次获取子级目录下是否有子级目录
                sub2_node = Mulu.objects.filter(parent_id=sub.id)
                if sub2_node:
                    for sub2 in sub2_node:
                        source_list += TdsdResourceList.objects.filter(resource_cate=sub2.id)
                else:
                    source_list += TdsdResourceList.objects.filter(resource_cate=sub.id)
        else:
            source_list = TdsdResourceList.objects.filter(resource_cate=id)
            print(source_list)
        data = serializers.serialize('json', source_list)
        msg = 'success'
        response_data = {'code': 0, 'msg': msg, 'data': data}
        return JsonResponse(response_data)
    except Exception:
        response_data = {'code': 1, 'msg': msg}
        return JsonResponse(response_data)


def add_rootdir(request):
    """超级管理员添加根目录"""
    msg = 'failure'
    name = request.POST.get('name')
    try:
        mulu = Mulu()
        mulu_obj = Mulu.objects.filter(name = name,isdelete=0,parent_id=None)
        if not mulu_obj:
            mulu.parent_id = None
            mulu.name = name
            mulu.user_id = request.session['user_id']
            # mulu.user_id = 1
            mulu.save()
            msg = 'success'
            response_data = {'code': 0, 'msg': msg}
            return JsonResponse(response_data)
        else:
            response_data = {'code': 2, 'msg': msg}
            return JsonResponse(response_data)
    except Exception:
        response_data = {'code': 1, 'msg': msg}
        return JsonResponse(response_data)
@csrf_exempt
def getcatelist(request,cateid):
    data={}
    result=Mulu.objects.filter(parent=cateid).filter(isdelete=0)
    for i in result:
        data.setdefault('data',[]).append({
            "id":i.id,
            "name":i.name
        })
    data['code']=0
    data['msg']=""
    return JsonResponse(data)